<?php

declare(strict_types=1);

namespace App\Controller\Backend;

use App\Constants\ReturnCode;
use App\Exception\BusinessException;
use App\Request\LoginRequest;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\RequestMapping;
use App\Controller\AbstractController;
use App\Service\UserService;
use App\Model\Authentication\Admin as AdminModel;
use Psr\SimpleCache\CacheInterface;

#[Controller]
class AuthController extends AbstractController
{
    #[Inject]
    protected UserService $userService;

    #[Inject]
    protected AdminModel $adminModel;

    #[Inject]
    protected CacheInterface $cache;

    #[RequestMapping(path: 'login', methods: 'POST')]
    public function login(LoginRequest $loginRequest)
    {
        $validated = $loginRequest->validated();

        $username = $validated['username'];
        $password = $validated['password'];

        $model = $this->adminModel->where(['username' => $username])->first();

        if (empty($model)) return $this->result(ReturnCode::INVALID_PARAMS);

        $store_password = $model->password;

        if (md5($password) != $store_password) return $this->result(ReturnCode::INVALID_PARAMS);

        // 生成token
        $token = md5('user:' . $model->id);

        $real_ip = $this->request->getHeaders()['x-real-ip'][0] ?? '';

        // 修改最后登录时间和ip
        $model->last_login_ip   = $real_ip;
        $model->last_login_time = date('Y-m-d H:i:s');

        $model->save();

        $this->cache->set('Authorization:' . $token, json_encode($model->toArray(), JSON_UNESCAPED_UNICODE), 60 * 60 * 4);

        return $this->result(ReturnCode::SUCCESS, ['Authorization' => $token], '登陆成功');
    }

    #[RequestMapping(path: 'logout', methods: 'POST')]
    #[Middleware(\App\Middleware\AuthMiddleware::class)]
    public function logout()
    {
        $token = $this->request->header('Authorization', '');

        $this->cache->delete('Authorization:' . $token);

        return $this->result(ReturnCode::SUCCESS, [], '登陆失败');
    }
}
